import 'dart:ui';
import 'package:liuxlcommon/lget/lget.dart';
import 'package:liuxlcommon/util/string_utils.dart';
import 'package:ladder_cash/app/app.dart';
import 'package:ladder_cash/app/com/view/webview/my_web/my_web_page.dart';
import 'package:ladder_cash/app/key_mix.dart';
import 'package:ladder_cash/app/page/component/decoration_bg.dart';
import 'package:ladder_cash/app/page/product_detail/authentication_page.dart';
import 'package:ladder_cash/config/super_theme.dart';
import 'package:ladder_cash/generated/l10n.dart';
import 'package:ladder_cash/value/app_colors.dart';
import 'package:ladder_cash/value/app_const.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:liuxlcommon/util/toast_util.dart';
import 'package:liuxlcommon/view/loading_view.dart';
import 'package:liuxlcommon/view/lxl_widget.dart';
import 'package:liuxlcommon/view/my_box.dart';
import 'package:liuxlcommon/view/my_style.dart';
import 'package:liuxlcommon/lget/LState.dart';
import 'package:ladder_cash/generated/assets.dart' as myAssets;
import 'package:ladder_cash/value/app_lstyle.dart';

import '../../../Global.dart';
import '../../../gen/assets.gen.dart';
import '../../../library/src/logger.dart';
import '../component/common.dart';
import '../component/product_detail.dart';
import 'product_detail_logic.dart';

///产品详情页面
class ProductDetailPage extends StatefulWidget {
  ProductDetailPage({super.key});

  @override
  _ProductDetailPageState createState() => _ProductDetailPageState();
}

class _ProductDetailPageState extends LState<ProductDetailPage>
    with RouteAware {
  final logic = Get.put(ProductDetailLogic());
  final GlobalKey<RefreshIndicatorState> _indicatorKey =
      GlobalKey<RefreshIndicatorState>();

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    App.routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  get init {}
  get cerHeight {
    if (logic.verifyList.length > 4) {
      return 372.w;
    } else if (logic.verifyList.length > 2) {
      return 290.w;
    } else {
      return 190.w;
    }
  }

  get rzCount {
    int c = 0;
    for (dynamic item in logic.verifyList ?? []) {
      if (item['status'.hx] == 1) {
        c++;
      }
    }
    return c;
  }

  @override
  get body => GetBuilder<ProductDetailLogic>(builder: (logic) {
        return Scaffold(resizeToAvoidBottomInset: true, body: getDetail());
      });

  getDetail() {
    return Container(
      width: Global.width,
      height: Global.height,
      decoration:
          BoxDecoration(image: getDecorationBg(Assets.home.home95251Bg.path)),
      child: Column(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          getProductDetail(
              isShowRight: true,
              amountRange: productDetail?['amount'.hx],
              loanRate: tag1['text'.hx],
              loanRateDes: tag1['title'.hx],
              termInfo: tag2['text'.hx],
              termInfoDes: tag2['title'.hx],
              title: productDetail?['productName'.hx] ??
                  S.current.certifcationDetails),
        Expanded(
          child: Container(
            height: cerHeight,
            padding: const EdgeInsets.all(12),
            margin: EdgeInsets.symmetric(horizontal: 12.w),
            decoration: BoxDecoration(
              image: getDecorationBg(Assets.home.home9527Bg.path),
            ),
            child: RefreshIndicator(
              key: _indicatorKey,
              color: AppColors.primaryColor,
              onRefresh: () async => await logic.getDetailData(refresh: true),
              child: ListView(padding: EdgeInsets.zero, children: [
                Column(
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset(
                          Assets.home.homeCBook.path,
                          width: 34.w,
                          height: 34.w,
                        ),
                        4.lsw,
                        middleFont(S.current.authenticationDetails,
                            fontsize: 24.sp,
                            fontFamily: 'italic',
                            fontWeight: FontWeight.w900)
                      ],
                    ),
                    20.lsh,
                    wrapLists
                  ],
                )
              ]),
            ),
          ),
        ),
          20.lsh,
          Column(
            children: [
              if (StringUtils.isNotEmpty(
                  logic.detailData?['agreement'.hx]?['urlLink'.hx])) xyBox,
              Container(
                height: 50.w,
                width: Global.width,
                alignment: Alignment.center,
                margin: EdgeInsets.only(
                    left: 16.w,
                    right: 16.w,
                    bottom: LGet.bottomPadding(context) + 10.w),
                child: commonBtn(productDetail['buttonText'.hx], callback: () {
                  if(logic.agree){
                    if (logic.isCompleteAll) {
                      logic.borrowMoney();
                      // Get.back();
                    } else {
                      Get.to(AuthenticationPage(), arguments: {
                        'productData': logic.detailData,
                        'product_id': logic.product_id,
                        'isBack': false
                      });
                    }
                  }else{
                    ToastUtils.toast(App.localeEn
                        ? "Please read and agree to the Agreement"
                        : "Please read and agree to the Agreement");
                  }

                }),
              ),
            ],
          )
        ],
      ),
    );
  }

  get bottomBox =>
      LText.easy(productDetail['buttonText'.hx], 18.sp, fw6, Colors.white)
          .style(rzBtnSty)
          .margin()
          .onTapL(() {});

  get productDetail => logic.detailData?['productDetail'.hx] ?? {};

  get xyBox => LRow(
        lStyle: LStyle(
            width: double.infinity,
            margin: EdgeInsets.only(bottom: 12.w),
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center),
        children: [
          LImage(
            logic.agree ? Assets.login.checked.path : Assets.login.check.path,
            lStyle: LStyle(
                height: 15.w, margin: EdgeInsets.symmetric(horizontal: 2.w)),
            onTap: () {
              logic.agree = !logic.agree;
              logic.update();
            },
          ),
          LSizeBoxWidth(2.w),
          LText.easy(
              S.current.iHave, 14.sp, FontWeight.w500, SuperTheme.whiteInput),
          LSizeBoxWidth(2.w),
          InkWell(
              child: Text(logic.detailData?['agreement'.hx]?['title'.hx],
                  style: TextStyle(
                      fontWeight: FontWeight.w700,
                      color: SuperTheme.secondPrimary,
                      fontSize: 14.sp)),
              onTap: () {
                Get.to(MyWebPage(
                    url: logic.detailData?['agreement'.hx]?['urlLink'.hx]));
              })
        ],
      );

  get tag1 => productDetail['columnText'.hx]?['tag1'.hx];

  get tag2 => productDetail['columnText'.hx]?['tag2'.hx];

  Widget get cardBox => LColumn.eazy([
        15.lsh,
        LRow.eazy([
          15.lsw,
          LImage.easy(productDetail['productLogo'.hx], 25.w, 26.w),
          10.lsw,
          LText.easy(productDetail['productName'.hx] + '*productName#', 15.sp,
                  null, Colors.white)
              .flex(1)
        ]),
        13.lsh,
        LText.easy(productDetail['amountDesc'.hx] + '*amountDesc#', 15.sp, fw4,
                Colors.white)
            .size(null, 18.w),
        7.lsh,
        LText.easy(productDetail?['amount'.hx] + '*amount#', 40.sp, fw7,
                Colors.white)
            .size(null, 48.w),
        10.lsh,
        LRow.eazy([
          car2v(tag1['title'.hx] + '*tag1#', tag1['text'.hx] + '*text#'),
          3.lsw,
          car2v(tag2['title'.hx] + '*tag2#', tag2['text'.hx] + '*text#'),
        ])
      ]).bgImg(myAssets.Assets.molopNewDecar).size(345.w, 172.w);

  Widget car2v(title, value) => LRow.eazy([
        LText.easy(title + ":", 11.sp, fw4, Colors.white),
        // LImage.easy(Assets.iconDetailic, 17.w, 22.w),
        // 10.lsw,
        LText.easy(value, 11.sp, fw4, Colors.white)
      ]).center().flex(1);

  get wrapLists => LoadingView(
        isPullDown: true,
        future: () => logic.getDetailData(),
        datas: logic.verifyList,
        onSuccess: () {
          logic.update();
        },
        body: () {
          List<Widget> items = [];
          for (dynamic item in logic.verifyList ?? []) {
            items.add(itemView(item, item['status'.hx] == 1));
          }
          return Wrap(
            spacing: 13.w,
            runSpacing: 16.0,
            children: items,
          );
        },
      );

  Widget itemView(item, check) {
    var isCur =
        logic.detailData?['nextStep'.hx]?['taskType'.hx] == item['taskType'.hx];
    return InkWell(
      onTap:(){
        logic.next(item: item);
      } ,
      child: Stack(children: [
        Container(
          padding: EdgeInsets.all(12.w),
          width: 150.w,
          height: 90.w,
          decoration:
              BoxDecoration(image: getDecorationBg(Assets.home.homeCBg.path)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              LImage.easy(
                  check ? myAssets.Assets.molopNewComplete : item['log'.hx],
                  19.w,
                  19.w),
              LText.easy((item['title'.hx]), 14.sp, fw4, AppColors.textColor),
              // LImage.easy(
              //     check? Assets.pcDetailarrowrightyes : Assets.pcDetailarrowright,
              //     15.w,
              //     21.w),
            ],
          ),
        ),
        Positioned(
            width: 18.w,
            height: 18.w,
            bottom: 20.w,
            right: 20.w,
            child: Image.asset(
              Assets.home.homeCR.path,
              width: 18.w,
              height: 18.w,
            )),
        Positioned(
            top: 8.w,
            right: 2.w,
            width: 74.w,
            height: 20.w,
            child: Container(
              padding: EdgeInsets.only(left: 20.w),
              width: 74.w,
              height: 20.w,
              child: LText.easy(
                  check ? S.current.completed : S.current.unfinished,
                  12.sp,
                  fw4,
                  Colors.white),
              decoration: BoxDecoration(
                  image: getDecorationBg(check
                      ? Assets.home.homeCC.path
                      : Assets.home.homeCUn.path)),
            )),
      ]),
    );
  }

  @override
  void didPopNext() {
    _indicatorKey.currentState?.show();
  }

  @override
  void dispose() {
    Get.delete<ProductDetailLogic>();
    App.routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  // TODO: implement finish
  get finish {}
}
